package com.woniu.platform.service.impl;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.customer.entity.Customer;
import com.woniu.customer.mapper.CustomerMapper;
import com.woniu.platform.entity.PlatformOrderForm;
import com.woniu.platform.entity.PlatformShop;
import com.woniu.platform.mapper.PlatformOrderFormMapper;
import com.woniu.platform.mapper.PlatformShopMapper;
import com.woniu.platform.service.PlatformShopService;
import com.woniu.redisson.DistributedRedisLock;
import com.woniu.util.utils.HttpResult;
import com.woniu.util.utils.RequestResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class PlatformShopServiceImpl implements PlatformShopService {

    @Autowired(required = false)
    private PlatformShopMapper shopMapper;
    @Autowired(required = false)
    private StringRedisTemplate redisTemplate;

    @Autowired(required = false)
    private PlatformOrderFormMapper OrderFormMapper;

    @Autowired(required = false)
    private CustomerMapper customerMapper;

    @Override
    public HttpResult insertGood(PlatformShop platformShop) {
        redisTemplate.delete("shop");
        int re = shopMapper.insert(platformShop);
        if (re>0){
            try {
                Thread.sleep(5);
                redisTemplate.delete("shop");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return new HttpResult().ok();
        }else{
            return new HttpResult().fail();
        }
    }

    @Override
    public HttpResult updateGood(PlatformShop platformShop) {
        redisTemplate.delete("shop:"+platformShop.getId());
        redisTemplate.delete("shop");
        int re = shopMapper.updateById(platformShop);
        if(re>0){
            try {
                Thread.sleep(5);
                redisTemplate.delete("shop:"+platformShop.getId());
                redisTemplate.delete("shop");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return new HttpResult().ok();
        }else{
            return new HttpResult().fail();
        }
    }

    @Override
    public HttpResult selectGoodById(int goodId) {
        String s = redisTemplate.opsForValue().get("shop:" + goodId);
        if(s != null && "".equals(s)) {
            PlatformShop good = JSON.parseObject(s, PlatformShop.class);
            return new HttpResult().ok(good);
        }else{
            Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", "lock", 1, TimeUnit.SECONDS);
            try {
                if (lock) {
                    PlatformShop good = shopMapper.selectById(goodId);
                    if (good == null){
                        redisTemplate.opsForValue().set("shop:"+goodId,"");
                    }else{
                        redisTemplate.opsForValue().set("shop:"+goodId,JSON.toJSONString(good),1,TimeUnit.DAYS);
                    }
                    return new HttpResult().ok(good);
                }else{
                    return new HttpResult().ok("系统繁忙");
                }
            } catch (Exception e) {
                e.printStackTrace();
                return new HttpResult().fail();
            } finally {
                redisTemplate.delete("lock");
            }
        }
    }

    @Override
    public HttpResult selectGoods(RequestResult<PlatformShop> requestResult) {
        String s = redisTemplate.opsForValue().get("shop");
        if(s != null && "".equals(s)) {
            PageHelper.startPage(requestResult.getPageNum(), requestResult.getPageSize());
            List<PlatformShop> list = JSON.parseArray(s, PlatformShop.class);
            PageInfo pageInfo = new PageInfo(list);
            return new HttpResult().ok(pageInfo);
        }else {
            Boolean lock = redisTemplate.opsForValue().setIfAbsent("shopLock", "shopLock", 1, TimeUnit.SECONDS);
            try {
                if (lock) {
                    PageHelper.startPage(requestResult.getPageNum(), requestResult.getPageSize());
                    List<PlatformShop> list = shopMapper.queryGoods(requestResult.getData().getGoodName(), requestResult.getData().getState());
                    PageInfo pageInfo = new PageInfo(list);
                    if(list.size() > 0 && list !=null ){
                        redisTemplate.opsForValue().set("shop",JSON.toJSONString(list),1,TimeUnit.DAYS);
                    }else{
                        redisTemplate.opsForValue().set("shop","");
                    }
                    return new HttpResult().ok(pageInfo);
                }else{
                    return new HttpResult().ok("系统繁忙");
                }
            } catch (Exception e) {
                e.printStackTrace();
                return new HttpResult().fail();
            } finally {
                redisTemplate.delete("lock");
            }
        }
    }

    @Override
    public HttpResult exchangeGoods(PlatformOrderForm platformOrderForm) {
        String key = "shopLock";
        try {
            //设置锁
            DistributedRedisLock.acquire(key);
            //根据订单商品id查询商品
            PlatformShop good = shopMapper.selectById(platformOrderForm.getGoodId());
            //根据订单用户id查询用户
            Customer customer = customerMapper.selectById(platformOrderForm.getCustomerId());
            //判断商品库存以及用户积分余额
            if(good.getCount()< platformOrderForm.getAmount() || customer.getGrade()<platformOrderForm.getConsumeGrade()){
                return new HttpResult().fail();
            }else{
                    good.setCount(good.getCount()-platformOrderForm.getAmount());
                    this.updateGood(good);///扣减商品库存
                    //扣减用户积分
                    customer.setGrade(customer.getGrade() - platformOrderForm.getConsumeGrade());
                    customerMapper.updateCustomerinformation(customer);
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    platformOrderForm.setExchangeTime(dateFormat.format(new Date()));
                    OrderFormMapper.insert(platformOrderForm);//新增订单
                    return new HttpResult().ok();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DistributedRedisLock.release(key);
        }
        return new HttpResult().fail();
    }
}
